// pages/tradingArea/addCoupon.js
const controller = require("../controllers/Controller").controller

const limitMoney = require("../../utils/util").limitMoney

Page({

  /**
   * 页面的初始数据
   */
  data: {
    payTypeList: [{
      name: "无限制",
      id: 0
    }, {
      name: "单次购买",
      id: 1
    }],
    activitySelectList:[{
      name: "系统默认",
      id: 0
    }, {
      name: "自定义",
      id: 1
    }],
    couponTypeList:[{
      name: "代金券",
      id: 0
    }, {
      name: "限时限产品券",
      id: 2
    }],
    noSelectIcon: 'https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/account/20210810/874665097627172864.png',
    selectedIcon: 'https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/account/20210810/874665118292508672.png',
    selectIndex: 0,
    value: {
      shopId: "",
      couponType: 0,
      type: "",
      timeState: 1,
      name: "",
      price: "",
      desc: "",
      effectiveStartTime: "",
      effectiveEndTime: "",
      ids: "",
      goodsArrayJson: '',
      payType: 0,
      num: '',
      cost: "",
      image:"",
      useRules:""
    },
    price2: "",
    lowPrice: "",
    profitDate:"",
    shareReward:"",
    activityRuleIndex:0,
    useRules:'',
    openGoHome:0,
    openPayRecord :0,
    openLeaderboard :0,
  },
  //上传图片
  uploadImg() {
    let that = this;
    wx.chooseImage({
      count: 1,
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        const tempFiles = res.tempFiles;
        // if (tempFiles[0].size > 1024 * 1024) {
        //   wx.showToast({
        //     title: '单张图片大不能超过1MB',
        //     icon: 'none',
        //     duration: 2000
        //   })
        //   return
        // }
        wx.uploadFile({
          url: 'https://www.xlshhr.com/beauty-industry/api/img/uploadFile',
          filePath: tempFilePaths[0],
          name: 'image',
          formData: {
            'sessionId': wx.getStorageSync("usertoken")
          },
          success(res) {
            console.log(res);
            let src = JSON.parse(res.data)
            that.setData({
              'value.image': src.data
            })
          }
        })
      }
    })
  },
  //选择支付限制
  selectPayType(e) {
    if (this.data.id) {
      return
    }
    let index = e.currentTarget.dataset.index
    this.setData({
      "value.payType": this.data.payTypeList[index].id
    })
  },

  // 选择活动规则
  selectActivityRule(e){
    let index=e.currentTarget.dataset.index
    this.setData({
      activityRuleIndex:index
    })
  },

  // 获取输入活动规则
  getUseRules(e){
    this.setData({
      'value.useRules':e.detail.value
    })
  },

  selectCouponType(e){
    if (this.data.id) {
      return
    }
    let index = e.currentTarget.dataset.index
    this.setData({
      "value.couponType": this.data.couponTypeList[index].id
    })
    if(this.data.value.couponType===0){
      this.setData({
        chooseProduct:[]
      })
    }
  },

  //获取用户输入分享奖励
  getShareReward(e){
    let regExp=/^\d+\.$/
    if(regExp.test(e.detail.value)){
      this.setData({
        shareReward:e.detail.value
      })
      return
    }
    if(e.detail.value>this.data.profitDate.rewardProportion){
      wx.showToast({
        icon:"none",
        title: '用户分享奖励不能大于门店剩余分配比例',
      })
      this.setData({
        shareReward:this.data.profitDate.rewardProportion
      })
      return
    }
    this.setData({
      shareReward:parseFloat(e.detail.value)
    })
  },

  //获取分佣比例列表
  getShareProfitList(){
    if(this.data.type!=2&&this.data.type!=4&&this.data.type!=5){
      return
    }
    let value={}
    value.type="S"
    value.state=this.data.type
    controller.getShareProfitList(value).then(res=>{
      this.setData({
        profitDate:res.data
      })
    })
  },

  getNumber(e) {
    this.setData({
      'value.num': parseInt(e.detail.value)
    })
  },
  addGoods() {
    let that=this
    let type = this.data.type
    if (type == 2||type == 3||type == 4||type == 5) {
      wx.navigateTo({
        url: '/pages/settlement/AddGoods/AddGoods?nowList='+JSON.stringify(that.data.chooseProduct)
      })
    } else {
      wx.navigateTo({
        url: '/pages/settlement/AddOneGoods/AddOneGoods'
      })
    }
  },

  //获取优惠券名称
  getCouponName(e) {
    this.setData({
      'value.name': e.detail.value
    })
  },
  //选择券有效期
  // selectCouponTime(e){
  //   let index=e.currentTarget.dataset.index
  //   this.setData({
  //     'value.timeState':index
  //   })
  // },

  switchGoHomeType(e) {
    this.setData({
      openGoHome: e.detail.value,
    })
  },
  switchPayRecord(e) {
    this.setData({
      openPayRecord : e.detail.value,
    })
  },
  switchLeaderboard(e) {
    this.setData({
      openLeaderboard : e.detail.value,
    })
  },

  bindDateChange(e) {
    this.setData({
      effectiveStartTime:e.detail.value,
      'value.effectiveStartTime': e.detail.value+" "+'00:00:00'
    })
  },

  bindDateChange2(e) {
    this.setData({
      effectiveEndTime:e.detail.value,
      'value.effectiveEndTime': e.detail.value+" "+'23:59:59'
    })
  },

  bindDateChange3(e) {
    this.setData({
      startTime:e.detail.value,
      'value.startTime': e.detail.value+" "+'00:00:00'
    })
  },

  bindDateChange4(e) {
    this.setData({
      endTime: e.detail.value,
      'value.endTime': e.detail.value+" "+'23:00:00'
    })
  },

  //获取优惠券面值
  getCouponPrice(e) {
    this.setData({
      'value.price': limitMoney(e.detail.value)
    })
  },

  //获取优惠券描述
  getCouponDesc(e) {
    this.setData({
      'value.desc': e.detail.value
    })
  },

  //获取抵扣券面值
  getCouponMoney(e){
    this.setData({
      'value.cost': limitMoney(e.detail.value)
    })
  },

  //删除选中商品
  delGoods(e) {
    let index = e.currentTarget.dataset.index
    let list = this.data.chooseProduct
    list.splice(index, 1)
    this.setData({
      chooseProduct: list
    })
    this.computedCost()
  },

  //新增优惠券
  saveCoupon() {
    let that = this
    let subValue = {}
    if (this.data.type == 6) {
      let value = this.data.value
      if (!value.name) {
        wx.showToast({
          icon: "none",
          title: '请输入优惠券名称',
          duration: 1500
        })
        return
      } else if (value.timeState === 1 && (!value.effectiveStartTime || !value.effectiveEndTime)) {
        wx.showToast({
          icon: "none",
          title: '请选择有效时间',
          duration: 1500
        })
        return
      }


      if (this.data.chooseProduct) {
        let list = []
        for (let i = 0; i < this.data.chooseProduct.length; i++) {
          list.push(this.data.chooseProduct[i].id)
        }
        value.ids = list.join(",")
      } else {
        wx.showToast({
          icon: "none",
          title: '请选择商品',
          duration: 1500
        })
        return
      }

      

      subValue.shopId = value.shopId
      subValue.type = value.type
      subValue.image = value.image
      subValue.timeState = value.timeState
      subValue.name = value.name
      subValue.price = value.price
      subValue.desc = value.desc
      subValue.effectiveStartTime = value.effectiveStartTime
      subValue.effectiveEndTime = value.effectiveEndTime
      subValue.ids = value.ids
      subValue.haveNum = 0 //0无限1有限

      if(value.id){
        subValue.id=value.id
        subValue.shopIds=value.shopId
        controller.updateBag(subValue).then(res=>{
          wx.showToast({
            icon: "none",
            title: '修改成功',
            duration: 1500
          })
          setTimeout(function () {
            wx.navigateBack({
              delta: 2,
            })
          }, 1000)
        })
      }else{
        controller.saveCoupon(subValue).then(res => {
          if (this.data.type==5||this.data.type==4||this.data.type==3||this.data.type==2) {
            wx.showToast({
              icon: "none",
              title: '请耐心等待代理商和管理员审核,审核中如果有什么疑问可以联系直属代理商',
              duration: 2000
            })
          }else{
            wx.showToast({
              icon: "none",
              title: '新增成功',
              duration: 1500
            })
          }
          setTimeout(function () {
            wx.navigateBack({
              delta: 2,
            })
          }, 1000)
        })
      }
    } else if(this.data.type == 4){
      let value=this.data.value
      if (!value.name) {
        wx.showToast({
          icon: "none",
          title: '请输入名称',
          duration: 1500
        })
        return
      } else if (!value.effectiveStartTime || !value.effectiveEndTime) {
        wx.showToast({
          icon: "none",
          title: '请选择有效时间',
          duration: 1500
        })
        return
      } else if (!value.price) {
        wx.showToast({
          icon: "none",
          title: '请输入出售价格',
          duration: 1500
        })
        return
      }else if (!value.cost) {
        wx.showToast({
          icon: "none",
          title: '请输入抵扣券面值',
          duration: 1500
        })
        return
      } else if (!value.startTime || !value.endTime) {
        wx.showToast({
          icon: "none",
          title: '请选择活动时间',
          duration: 1500
        })
        return
      } else if (!value.num) {
        wx.showToast({
          icon: "none",
          title: '请输入可销售数',
          duration: 1500
        })
        return
      } else if (this.data.type == 3 && (parseFloat(value.price) < this.data.lowPrice)) {
        wx.showToast({
          icon: "none",
          title: '出售价格不能少于' + that.data.lowPrice + "元",
          duration: 1500
        })
        return
      }
      else if (!value.image) {
        wx.showToast({
          icon: "none",
          title: '请上传缩略图',
          duration: 1500
        })
        return
      }

      if (this.data.chooseProduct) {
        let list = []
        let idsList = []
        for (let i = 0; i < this.data.chooseProduct.length; i++) {
          let goods = new Object()
          goods.num = this.data.chooseProduct[i].count
          goods.goodsId = this.data.chooseProduct[i].id
          goods.sort = 10
          list.push(goods)
          idsList.push(this.data.chooseProduct[i].id)
        }
        value.goodsArrayJson = JSON.stringify(list)
        value.ids = idsList.join(",")
      } else if(value.couponType===0){
        
      } else {
        wx.showToast({
          icon: "none",
          title: '请选择商品',
          duration: 1500
        })
        return
      }
      if(this.data.type==2||this.data.type==4||this.data.type==5){
        subValue.accountProportion = (this.data.shareReward||0)*100
      }
      
      // 排行榜隐藏开关和收益隐藏开关 
      subValue.openPayRecord  = this.data.openPayRecord ? 1 : 0
      subValue.openLeaderboard  = this.data.openLeaderboard ? 1 : 0

      subValue.shopId = value.shopId
      subValue.payType = value.payType
      subValue.type = value.type
      subValue.num = value.num
      subValue.img = value.image
      subValue.couponType = value.couponType
      subValue.timeState = value.timeState
      subValue.name = value.name
      subValue.price = value.price
      subValue.detailImg = value.detailImg
      subValue.payType = value.payType
      subValue.cost = value.cost
      subValue.effectiveStartTime = value.effectiveStartTime
      subValue.effectiveEndTime = value.effectiveEndTime
      subValue.effectiveTimeState = 1
      subValue.startTime = value.startTime
      subValue.endTime = value.endTime
      subValue.goodsArrayJson = value.goodsArrayJson
      subValue.ids = value.ids
      subValue.useRules=this.data.value.useRules
      subValue.useRulesType=this.data.activitySelectList[this.data.activityRuleIndex].id

      if(value.id){
        subValue.id=value.id
        subValue.shopIds=value.shopId
        controller.updateLimited(subValue).then(res=>{
          wx.showToast({
            icon: "none",
            title: '修改成功',
            duration: 1500
          })
          setTimeout(function () {
            wx.navigateBack({
              delta: 2,
            })
          }, 1000)
        })
      }else{
        controller.createTimeLimitCoupon(subValue).then(res=>{
          if (this.data.type==5||this.data.type==4||this.data.type==3||this.data.type==2) {
            wx.showToast({
              icon: "none",
              title: '请耐心等待代理商和管理员审核,审核中如果有什么疑问可以联系直属代理商',
              duration: 2000
            })
          }else{
            wx.showToast({
              icon: "none",
              title: '新增成功',
              duration: 1500
            })
          }
          setTimeout(function () {
            wx.navigateBack({
              delta: 2,
            })
          }, 2000)
        })
      }
    }else {
      let value=this.data.value
      if (!value.name) {
        wx.showToast({
          icon: "none",
          title: '请输入名称',
          duration: 1500
        })
        return
      } else if (!value.effectiveStartTime || !value.effectiveEndTime) {
        wx.showToast({
          icon: "none",
          title: '请选择有效时间',
          duration: 1500
        })
        return
      } else if (!value.price) {
        wx.showToast({
          icon: "none",
          title: '请输入出售价格',
          duration: 1500
        })
        return
      } else if (!value.startTime || !value.endTime) {
        wx.showToast({
          icon: "none",
          title: '请选择活动时间',
          duration: 1500
        })
        return
      } else if (!value.num) {
        wx.showToast({
          icon: "none",
          title: '请输入可销售数',
          duration: 1500
        })
        return
      } else if (this.data.type == 3 && (parseFloat(value.price) < this.data.lowPrice)) {
        wx.showToast({
          icon: "none",
          title: '出售价格不能少于' + that.data.lowPrice + "元",
          duration: 1500
        })
        return
      }
      // else if(!value.detailImg){
      //   wx.showToast({
      //     icon:"none",
      //     title: '请上传详情介绍图',
      //     duration:1500
      //   })
      //   return
      // }
      else if (!value.image) {
        wx.showToast({
          icon: "none",
          title: '请上传缩略图',
          duration: 1500
        })
        return
      }

      if (this.data.chooseProduct) {
        let list = []
        let idsList = []
        for (let i = 0; i < this.data.chooseProduct.length; i++) {
          let goods = new Object()
          goods.num = this.data.chooseProduct[i].count
          goods.goodsId = this.data.chooseProduct[i].id
          goods.sort = 10
          list.push(goods)
          idsList.push(this.data.chooseProduct[i].id)
        }
        value.goodsArrayJson = JSON.stringify(list)
        value.ids = idsList.join(",")
      } else {
        wx.showToast({
          icon: "none",
          title: '请选择商品',
          duration: 1500
        })
        return
      }

      if(this.data.type==2||this.data.type==4||this.data.type==5){
        subValue.accountProportion = (this.data.shareReward||0)*100
      }

      if(this.data.type==2||this.data.type==3){
        subValue.openGoHome = this.data.openGoHome? 1 : 0

      }
      // 排行榜隐藏开关和收益隐藏开关 
      subValue.openPayRecord  = this.data.openPayRecord ? 1 : 0
      subValue.openLeaderboard  = this.data.openLeaderboard ? 1 : 0

      subValue.shopId = value.shopId
      subValue.payType = value.payType
      subValue.type = value.type
      subValue.num = value.num
      subValue.img = value.image
      subValue.couponType = value.couponType
      subValue.timeState = value.timeState
      subValue.name = value.name
      subValue.price = value.price
      subValue.cost = value.cost
      subValue.detailImg = value.detailImg
      subValue.effectiveStartTime = value.effectiveStartTime
      subValue.effectiveEndTime = value.effectiveEndTime
      subValue.startTime = value.startTime
      subValue.endTime = value.endTime
      subValue.goodsArrayJson = value.goodsArrayJson
      subValue.ids = value.ids
      subValue.useRules=this.data.value.useRules
      subValue.useRulesType=this.data.activitySelectList[this.data.activityRuleIndex].id

      if(value.id){
        subValue.id=value.id
        subValue.shopIds=value.shopId
        controller.updateBag(subValue).then(res=>{
          wx.showToast({
            icon: "none",
            title: '修改成功',
            duration: 1500
          })
          setTimeout(function () {
            wx.navigateBack({
              delta: 2,
            })
          }, 1000)
        })
      }else{
        controller.createHot(subValue).then(res => {
          if (this.data.type==5||this.data.type==4||this.data.type==3||this.data.type==2) {
            wx.showToast({
              icon: "none",
              title: '请耐心等待代理商和管理员审核,审核中如果有什么疑问可以联系直属代理商',
              duration: 2000
            })
          }else{
            wx.showToast({
              icon: "none",
              title: '新增成功',
              duration: 1500
            })
          }
          setTimeout(function () {
            wx.navigateBack({
              delta: 2,
            })
          }, 2000)
        })
      }

    }
  },

  //计算券包价值
  computedCost() {
    let list = this.data.chooseProduct
    let cost = 0
    if(this.data.type!=4){
      list.forEach(item => {
        cost = cost + item.count * item.price
      })
      this.setData({
        "value.cost": cost,
        "value.price": cost
      })
    }
  },

  //取消
  cancle() {
    wx.navigateBack()
  },

  //获取欢乐拼可填写最低价格
  getLowPrice() {
    controller.getAccountPinFail().then(res => {
      this.setData({
        lowPrice: (Math.ceil((0.01 / res.data.rewardProportion * 100) * 100)) / 100
      })
    })
  },

  //获取详情
  getCouponDetail(){
    if(this.data.type==2||this.data.type==3||this.data.type==4||this.data.type==5){
      controller.getActivityDetail({couponBagId:this.data.value.id}).then(res=>{
        let detail=res.data
        if(detail.effectiveStartTime){
          detail.effectiveStartTime=detail.effectiveStartTime.split(" ")[0]
          detail.effectiveEndTime=detail.effectiveEndTime.split(" ")[0]
        }
        if(detail.startTime){
          detail.startTime=detail.startTime.split(" ")[0]
          detail.endTime=detail.endTime.split(" ")[0]
        }
        if(detail.goodsList){
          detail.goodsList.forEach(item=>{
            item.image=item.goodsImage
            item.id=item.goodsId
            item.count=item.num
            item.type=item.goodsType
          })
          this.setData({
            chooseProduct:detail.goodsList
          })
        }
        detail.goodsList=''
        detail.shop=''
        this.setData({
          activityRuleIndex:detail.useRulesType,
          value:detail,
          openGoHome:detail.openGoHome,
          openPayRecord :detail.openPayRecord ,
          openLeaderboard :detail.openLeaderboard ,
          'value.image':detail.img
        })
      })
    }else{
      controller.getCouponDetail({couponId:this.data.value.id}).then(res=>{
        let detail=res.data
        if(detail.effectiveStartTime){
          detail.effectiveStartTime=detail.effectiveStartTime.split(" ")[0]
          detail.effectiveEndTime=detail.effectiveEndTime.split(" ")[0]
        }
        if(detail.startTime){
          detail.startTime=detail.startTime.split(" ")[0]
          detail.endTime=detail.endTime.split(" ")[0]
        }
        if(detail.goodsList){
          this.setData({
            chooseProduct:detail.goodsList
          })
        }
        detail.goodsList=''
        detail.shop=''
        this.setData({
          value:detail
        })
    })
    }
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      'value.shopId': wx.getStorageSync('shopId'),
    })
    if(options.type){
      this.setData({
        type: options.type,
        'value.type': options.type
      })
    }
    if (this.data.type == 3) {
      this.getLowPrice()
    }

    if(options.id){
      this.setData({
        "value.id":options.id
      })
      this.getCouponDetail()
    }

    this.getShareProfitList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }

  //上传活动介绍详情图
  uploadDetailImg() {
    let that = this;
    wx.chooseImage({
      count: 1,
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        const tempFiles = res.tempFiles;
        if (tempFiles[0].size > 1024 * 1024 * 20) {
          wx.showToast({
            title: '单张图片大不能超过20MB',
            icon: 'none',
            duration: 2000
          })
          return
        }
        wx.uploadFile({
          url: 'https://www.xlshhr.com/beauty-industry/api/img/uploadFile',
          filePath: tempFilePaths[0],
          name: 'image',
          formData: {
            'sessionId': wx.getStorageSync("usertoken")
          },
          success(res) {
            console.log(res);
            let src = JSON.parse(res.data)
            that.setData({
              'value.detailImg': src.data
            })
          }
        })
      }
    })
  },

  //打开预览图片
  openBigImg() {
    if (!this.data.value.detailImg) {
      return
    }
    let that = this
    let list = []
    list.push(that.data.value.detailImg)
    wx.previewImage({
      current: that.data.value.detailImg,
      urls: list
    })
  },
})